import random
import sys


class User:
    def __init__(self, account_id, account_type, name, password, address, balance, bank_name):
        self.account_id = account_id
        self.account_type = account_type  # 1:金卡 2:普通卡
        self.name = name
        self.password = password
        self.address = address
        self.balance = balance
        self.bank_name = bank_name

    def __str__(self):
        return (f"账号: {self.account_id}\n"
                f"姓名: {self.name}\n"
                f"账户类型: {'金卡' if self.account_type == 1 else '普通卡'}\n"
                f"地址: {self.address['country']}{self.address['province']}{self.address['street']}{self.address['house_number']}\n"
                f"余额: {self.balance}元\n"
                f"开户行: {self.bank_name}")


class Bank:
    def __init__(self, bank_name):
        self.bank_name = bank_name
        self.users = {}
        self.max_users = 100

    def generate_account_id(self):
        """生成8位唯一账号"""
        while True:
            account_id = str(random.randint(10000000, 99999999))
            if account_id not in self.users:
                return account_id

    def open_account(self, account_type, name, password, address, initial_balance=0):
        """开户功能"""
        # 检查用户库是否已满
        if len(self.users) >= self.max_users:
            return 3, None

        # 创建新用户
        account_id = self.generate_account_id()
        new_user = User(account_id, account_type, name, password, address, initial_balance, self.bank_name)
        self.users[account_id] = new_user
        return 1, account_id  # 成功时返回账号

    def deposit(self, account_id, amount):
        """存款功能"""
        user = self.users.get(account_id)
        if not user:
            return False
        user.balance += amount
        return True

    def withdraw(self, account_id, password, amount):
        """取款功能"""
        user = self.users.get(account_id)
        if not user:
            return 1  # 账号不存在
        if user.password != password:
            return 2  # 密码错误
        if user.balance < amount:
            return 3  # 余额不足
        user.balance -= amount
        return 0  # 成功

    def transfer(self, from_id, to_id, password, amount):
        """转账功能"""
        from_user = self.users.get(from_id)
        to_user = self.users.get(to_id)
        if not from_user or not to_user:
            return 1  # 账号不存在
        if from_user.password != password:
            return 2  # 密码错误
        if from_user.balance < amount:
            return 3  # 余额不足

        # 检查转账限额
        if from_user.account_type == 1 and amount > 50000:
            return 4  # 超过金卡限额
        if from_user.account_type == 2 and amount > 20000:
            return 5  # 超过普通卡限额

        # 执行转账
        from_user.balance -= amount
        to_user.balance += amount
        return 0  # 成功

    def query_account(self, account_id, password):
        """查询账户信息"""
        user = self.users.get(account_id)
        if not user:
            print("该用户不存在")
            return
        if user.password != password:
            print("密码错误")
            return
        print(user)


class ATM:
    def __init__(self, bank):
        self.bank = bank

    def display_menu(self):
        """完全复现图片中的菜单界面"""
        print("*" * 50)
        print("*" + "中国农业银行账户管理系统".center(48) + "*")
        print("*" * 50)
        print("*" + "选项".center(48) + "*")
        print("*" + "1.开户".center(48) + "*")
        print("*" + "2.存钱".center(48) + "*")
        print("*" + "3.取钱".center(48) + "*")
        print("*" + "4.转账".center(48) + "*")
        print("*" + "5.查询".center(48) + "*")
        print("*" + "6.Bye".center(48) + "*")
        print("*" * 50)

    def run(self):
        """运行ATM系统"""
        while True:
            self.display_menu()
            choice = input("请选择操作(1-6): ")

            if choice == '1':
                self.open_account()
            elif choice == '2':
                self.deposit()
            elif choice == '3':
                self.withdraw()
            elif choice == '4':
                self.transfer()
            elif choice == '5':
                self.query()
            elif choice == '6':
                print("感谢使用，再见！")
                sys.exit()
            else:
                print("无效选择，请重新输入！")
            print()  # 添加空行分隔操作

    def open_account(self):
        """处理开户操作"""
        print("\n--- 开户 ---")
        while True:
            account_type = input("账户类型 (1:金卡 2:普通卡): ")
            if account_type in ['1', '2']:
                account_type = int(account_type)
                break
            print("输入错误，请重新选择账户类型")

        name = input("姓名: ")

        while True:
            password = input("设置6位数字密码: ")
            if len(password) == 6 and password.isdigit():
                password = int(password)
                break
            print("密码必须是6位数字")

        print("\n请输入地址信息:")
        country = input("国家: ")
        province = input("省份: ")
        street = input("街道: ")
        house_number = input("门牌号: ")
        address = {
            'country': country,
            'province': province,
            'street': street,
            'house_number': house_number
        }

        while True:
            try:
                initial_balance = int(input("初始存款金额: "))
                break
            except ValueError:
                print("请输入有效的金额数字")

        result, account_id = self.bank.open_account(account_type, name, password, address, initial_balance)

        if result == 1:
            print("\n开户成功！")
            print(f"您的账号是: {account_id} (请务必记好此账号)")
            print(f"初始余额: {initial_balance}元")
        elif result == 3:
            print("开户失败：用户库已满")

    def deposit(self):
        """处理存款操作"""
        print("\n--- 存款 ---")
        account_id = input("账号: ")

        while True:
            try:
                amount = int(input("存款金额: "))
                if amount > 0:
                    break
                print("存款金额必须大于0")
            except ValueError:
                print("请输入有效的金额数字")

        if self.bank.deposit(account_id, amount):
            user = self.bank.users.get(account_id)
            print(f"\n存款成功！")
            print(f"当前余额: {user.balance}元")
        else:
            print("存款失败：账号不存在")

    def withdraw(self):
        """处理取款操作"""
        print("\n--- 取款 ---")
        account_id = input("账号: ")

        try:
            password = int(input("密码: "))
        except ValueError:
            password = -1  # 确保验证失败

        while True:
            try:
                amount = int(input("取款金额: "))
                if amount > 0:
                    break
                print("取款金额必须大于0")
            except ValueError:
                print("请输入有效的金额数字")

        result = self.bank.withdraw(account_id, password, amount)

        if result == 0:
            user = self.bank.users.get(account_id)
            print(f"\n取款成功！")
            print(f"当前余额: {user.balance}元")
        elif result == 1:
            print("取款失败：账号不存在")
        elif result == 2:
            print("取款失败：密码错误")
        elif result == 3:
            print("取款失败：余额不足")

    def transfer(self):
        """处理转账操作"""
        print("\n--- 转账 ---")
        from_id = input("转出账号: ")
        to_id = input("转入账号: ")

        try:
            password = int(input("转出账号密码: "))
        except ValueError:
            password = -1  # 确保验证失败

        while True:
            try:
                amount = int(input("转账金额: "))
                if amount > 0:
                    break
                print("转账金额必须大于0")
            except ValueError:
                print("请输入有效的金额数字")

        result = self.bank.transfer(from_id, to_id, password, amount)

        if result == 0:
            from_user = self.bank.users.get(from_id)
            print("\n转账成功！")
            print(f"转出账号余额: {from_user.balance}元")
        elif result == 1:
            print("转账失败：账号不存在")
        elif result == 2:
            print("转账失败：密码错误")
        elif result == 3:
            print("转账失败：余额不足")
        elif result == 4:
            print("转账失败：超过金卡转账限额(5万)")
        elif result == 5:
            print("转账失败：超过普通卡转账限额(2万)")

    def query(self):
        """处理查询操作"""
        print("\n--- 查询 ---")
        account_id = input("账号: ")

        try:
            password = int(input("密码: "))
        except ValueError:
            password = -1  # 确保验证失败

        self.bank.query_account(account_id, password)
        print()  # 添加空行分隔操作


# 创建银行实例
bank = Bank("中国农业银行昌平沙河支行")
atm = ATM(bank)

# 启动ATM系统
if __name__ == "__main__":
    print("\n" + "=" * 50)
    print("欢迎使用中国农业银行账户管理系统".center(48))
    print("=" * 50)
    atm.run()